package com.maple.phoneward.service;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

import com.maple.phoneward.activity.R;
import com.maple.phoneward.constants.Constants;
import com.maple.phoneward.utils.AppUtil;
import com.maple.phoneward.utils.EmailUtil;
import com.maple.phoneward.utils.Logger;
import com.maple.phoneward.utils.StringUtil;

/**
 * SimService.java
 * 
 * @author YaJian Qiu
 * @time 2013-3-30 上午9:55:25<br>
 *       本类描述：SIM卡服务
 * 
 */
public class SimService extends Service {

	private static final String TAG = "SimService";

	class MyBind extends Binder {

	}

	@Override
	public IBinder onBind(Intent intent) {
		return new MyBind();
	}

	@Override
	public void onCreate() {
		Logger.d(TAG, "SIM卡服务创建");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Logger.d(TAG, "在SIM卡服务中执行命令");
		
		TimerTask task = new TimerTask() {
			
			@Override
			public void run() {
				boolean isSimChangeLocked = AppUtil.getFromSharedPreferences(SimService.this, Constants.IS_SIM_CHANGE_NOTIFY, Boolean.class);
				Logger.d(TAG, "换卡通知是否开启:"+isSimChangeLocked);
				//换卡通知
				if (isSimChangeLocked) {
					String lastNum = AppUtil.getFromSharedPreferences(SimService.this, Constants.CONFIG_PHONE_NUMBER);
					String currentNum = AppUtil.getPhoneNumber(SimService.this);
					// test
					currentNum = "15555215558";
					if (StringUtil.notEquals(lastNum, currentNum)) {
						Logger.d(TAG, "SIM卡被更换");
						String num1 = AppUtil.getFromSharedPreferences(SimService.this, Constants.CONFIG_SAFETY_PHONE_NUMBER_1);
						String num2 = AppUtil.getFromSharedPreferences(SimService.this, Constants.CONFIG_SAFETY_PHONE_NUMBER_2);
						String toSendTemp = AppUtil.getString(SimService.this, R.string.change_sim);
						String toSend = String.format(toSendTemp, currentNum);
						if (StringUtil.isNotEmpty(num1)) {
							AppUtil.sendMessage(num1, toSend);
						}
						if (StringUtil.isNotEmpty(num2)) {
							AppUtil.sendMessage(num2, toSend);
						}
						EmailUtil.sendEmail(SimService.this, AppUtil.getString(SimService.this, R.string.change_sim_email_title), toSend);
					} else {
						Logger.d(TAG, "SIM卡没有被更换");
					}
					//SimService.this.stopSelf();
				}
				
			}
		};
		Timer timer = new Timer();
		timer.schedule(task, 1000*6*3);//三分钟后执行

		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		Logger.d(TAG, "SIM卡服务销毁");
	}

}
